import store from "../store"
import {
	debounceImmediate
} from "./validate"
import {
	startEid
} from '@/mp_ecard_sdk/main'
import {
	EidToken,
	IsEidToken
} from "@/api/new_api.js"
import util from "./util"
class verificationClass {
	constructor() {
		this.countdownTime = store.state.app.countdownTime
		this.countdownInterval = store.state.app.countdownInterval
		this.eidtoken = ''
	}
	showModal(url = '/pages/home/index') {
		uni.showModal({
			// title: '提示',
			content: '尚未完成实名认证，请先完成实名，后进行操作',
			success: (res) => {
				if (res.confirm) {
					uni.setStorage({
						key: 'verification_redirect_url',
						data: url
					})
					this.verification()
				}
			}
		});
	}
	verification = debounceImmediate(async function() {
		try {
			let eidTokenData = await EidToken()
			const data = eidTokenData.data.data
			if (data) {
				this.eidtoken = data.EidToken;
			}
		} catch (error) {
			util.Tips({
				title: error.msg
			})
		}
		this.goSDK();

		
	})

	startCountdown(durationInSeconds) {
		
		let that = this
		let remainingTime = durationInSeconds;
		let timer = setInterval(() => {
			store.commit('setCountdownTime', remainingTime)
			if (store.state.app.countdownTime <= 0) {
				that.clearStorageHandle()
				return
			}
			remainingTime--
		}, 1000)
		store.commit('setCountdownInterval', timer)

	}
	clearStorageHandle() {
		clearInterval(store.state.app.countdownInterval);
		uni.removeStorageSync('verification_eidtoken'); // 删除认证token
		uni.removeStorageSync('countdownTime'); // 删除剩余倒计时时间
		store.commit('setCountdownInterval', null) //计时器变回空
	}
	goSDK() {
		let that = this;
		try {
			startEid({
				data: {
					token: this.eidtoken,
					enableEmbedded: true,
					allowFullScreen: false
				},
				verifyDoneCallback(res) {
					const {
						token,
						verifyDone
					} = res;
					that.getIsEidToken()
					// 已完成删除认证token
					if (verifyDone) {
						that.clearStorageHandle()
					}
					console.log('收到核身完成的res:', res);
					console.log('核身的token是:', token);
					console.log('是否完成核身:', verifyDone);
				},
			});
		} catch (error) {
			console.log(error, "调起失败");
			//TODO handle the exception
		}

	}
	getIsEidToken() {
		IsEidToken({
			eidToken: this.eidtoken
		}).then((res) => {
			util.Tips({
				title: res.msg
			})
			if (res.status == 200) {
				// 识别成功后跳转页面
				setTimeout(() => {
					const verification_redirect_url = uni.getStorageSync(
						'verification_redirect_url') || '/pages/home/index'
					util.JumpPath(verification_redirect_url, true)
					uni.removeStorageSync('verification_redirect_url')
				}, 700)
			}

		}).catch((err) => {
			util.Tips({
				title: err.msg
			})
		})
	}
}
export default new verificationClass